package cn.itsource.ymcc.service.impl;

import cn.itsource.domain.CourseDoc;
import cn.itsource.ymcc.feignclient.EsFeignClient;
import cn.itsource.ymcc.constant.RConst;
import cn.itsource.ymcc.domain.*;
import cn.itsource.ymcc.dto.CourseSaveDto;
import cn.itsource.ymcc.mapper.*;
import cn.itsource.ymcc.producer.CourserOnlineProducer;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICourseService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cff
 * @since 2024-06-11
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseResourceMapper courseResourceMapper;
    @Autowired
    private CourseSummaryMapper courseSummaryMapper;

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseCollectMapper courseCollectMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private EsFeignClient esFeignClient;

    @Autowired
    private CourserOnlineProducer producer;



    @Transactional
    @Override
    public boolean removeById(Serializable id) {
        courseDetailMapper.deleteById(id);
        courseMarketMapper.deleteById(id);
        courseResourceMapper.deleteById(id);
        courseSummaryMapper.deleteById(id);
        return super.removeById(id);
    }

    @Transactional
    @Override
    public void save(CourseSaveDto courseSaveDto) {
        courseSaveDto.getCourse().setStatus(RConst.Num.INT_0);
        courseSaveDto.getCourse().setChapterCount(RConst.Num.INT_0);
        //查询老师
        List<Long> teacharIds = courseSaveDto.getTeacharIds();

        List<Teacher> teachers = teacherMapper.selectBatchIds(teacharIds);
        String collect = teachers.stream().map(Teacher::getName)
                .collect(Collectors.joining(","));
        courseSaveDto.getCourse().setTeacherNames(collect);
        super.save(courseSaveDto.getCourse());

        Long courseId = courseSaveDto.getCourse().getId();
        CourseDetail courseDetail = courseSaveDto.getCourseDetail();
        courseDetail.setId(courseId);

        CourseMarket courseMarket = courseSaveDto.getCourseMarket();
        courseMarket.setId(courseId);
        //假设前端默认传的一个
        CourseResource courseResource = courseSaveDto.getCourseResource();
        courseResource.setCourseId(courseId);

        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(courseId);
        courseSummary.setCommentCount(RConst.Num.INT_0);
        courseSummary.setSaleCount(RConst.Num.INT_0);
        courseSummary.setViewCount(RConst.Num.INT_0);

        courseMarketMapper.insert(courseMarket);
        courseDetailMapper.insert(courseDetail);
        courseResourceMapper.insert(courseResource);
        courseSummaryMapper.insert(courseSummary);
        courseMapper.saveCourseTeacher(courseId,courseSaveDto.getTeacharIds());


    }

    /**
     * 课程发布，发布数据保存到ES中的
     * @param ids
     * @return
     */
    @Override
    public JsonResult onLineCourse(List<Long> ids) {
        //修改状态
        Course course = new Course();
        course.setStatus(RConst.Num.INT_1);
        course.setOnlineTime(new Date());
        // 提出需求说 如果已经上线会出现重复上线的情况怎么解决
        courseMapper.update(course,new LambdaQueryWrapper<Course>()
                .eq(Course::getStatus,RConst.Num.INT_0)
                .in(Course::getId,ids));
        List<CourseDoc> docs = getCourseDocs(ids);
        //远程调用 进行发布es
        esFeignClient.batchSave(docs);

        //使用mq去发送一个短信或邮箱 或者 站内信
        producer.sendMessage(ids);
        return JsonResult.success();

    }
    private List<CourseDoc> getCourseDocs(List<Long> ids) {
        //添加到es里面  自己构建courseDoc数据
        List<CourseDoc> docs = new ArrayList<>(ids.size());
        List<Course> courses = super.listByIds(ids);
        courses.forEach(item ->{
            CourseDoc courseDoc = new CourseDoc();
            BeanUtils.copyProperties(item,courseDoc);
            CourseType type = courseTypeMapper.selectById(item.getCourseTypeId());
            if(type != null){
                courseDoc.setCourseTypeName(type.getName());
            }
            courseDoc.setStartTime(item.getStartTime().getTime());
            courseDoc.setEndTime(item.getEndTime().getTime());
            courseDoc.setOnlineTime(item.getOnlineTime().getTime());

            CourseDetail courseDetail = courseDetailMapper.selectById(item.getId());
            BeanUtils.copyProperties(Optional.ofNullable(courseDetail).orElse(new CourseDetail()),courseDoc);

            CourseMarket courseMarket = courseMarketMapper.selectById(item.getId());
            BeanUtils.copyProperties(Optional.ofNullable(courseMarket).orElse(new CourseMarket()),courseDoc);
            courseDoc.setPrice(Optional.ofNullable(courseMarket.getPrice()).orElse(new BigDecimal(RConst.Num.INT_0)).doubleValue());
            courseDoc.setPriceOld(Optional.ofNullable(courseMarket.getPriceOld()).orElse(new BigDecimal(RConst.Num.INT_0)).doubleValue());

            CourseSummary courseSummary = courseSummaryMapper.selectById(item.getId());
            BeanUtils.copyProperties(Optional.ofNullable(courseSummary).orElse(new CourseSummary()),courseDoc);

            Integer integer = courseCollectMapper.selectCount(new LambdaQueryWrapper<CourseCollect>()
                    .eq(CourseCollect::getCourseId, item.getId()));
            courseDoc.setCollectCount(integer);
            docs.add(courseDoc);
        });
        return docs;
    }


    @Override
    public void updateById(CourseSaveDto courseSaveDto) {

    }
}
